package com.zrx.govern.component.easyexcel.starter.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * @author zhangxiaowei
 * @desc
 */
@Slf4j
public class IpUtils {

    private static final String UNKNOWN = "unknown";

    private static final String IP = "127.0.0.1";

    private static final String SIGN = ",";

    /**
     * 获取客户端IP地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        log.info("x-Original-Forwarded-For:" + request.getHeader("x-Original-Forwarded-For"));
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (IP.equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (Exception e) {
                    log.error("解析ip地址异常", e);
                }
                try {
                    ip = inet.getHostAddress();
                } catch (Exception e) {
                    log.error("解析ip地址异常", e);
                }
            }
        }
        if (StringUtils.isBlank(ip)) {
            ip = request.getHeader("x-Original-Forwarded-For");
        }
        int ipLenth = 15;
        // 多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > ipLenth) {
            if (ip.indexOf(SIGN) > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

}
